import { useEffect, useRef, useState } from 'react';
import { ActionType, BetaSchemaForm, ProFormInstance, ProTable, TableDropdown } from '@ant-design/pro-components';
import { App, Button, Form } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { isSuccessCode } from '@/utils/isSuccessCode';
import { getPageCount } from '@/utils/getPageCount';
import { filterObj } from '@/utils/filterObj';
import { roleTableConfig } from '@/views/Role/RoleTableConfig';
import { roleFormItem } from '@/views/Role/RoleFormItem';
import { RoleType } from '@/types/role';
import { createRole, deleteRole, getRoleList, updateRole } from '@/api/modules/role';
import { useWitTheme } from '@/hook';

export const Role = () => {
  const { modal, message } = App.useApp();
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [visible, setVisible] = useState<boolean>(false);
  const theme = useWitTheme();
  // 表格操作按钮
  const columnsOptions = (text: any, record: any, index: number, action: ActionType) => (
    <div>
      <Button
        type="link"
        key="editable"
        onClick={async () => {
          action?.startEditable?.(record.id);
        }}
      >
        编 辑
      </Button>
      <TableDropdown
        key="actionGroup"
        onSelect={e => console.log(e)}
        menus={[
          { key: 'menu', name: '分配菜单' },
          { key: 'permissions', name: '分配权限' },
        ]}
      />
    </div>
  );
  useEffect(() => {
    console.log(theme);
  }, [theme]);
  // 表单配置
  const [form] = Form.useForm<{ name: string; company: string }>();
  return (
    <div>
      <ProTable<RoleType>
        {...roleTableConfig}
        actionRef={actionRef}
        request={async (params, sort, filter) => {
          const c = params.current;
          delete params.current;
          params.pageNum = c;
          const { data, headers } = await getRoleList({ params });
          return {
            data: data.data,
            success: isSuccessCode(data),
            total: getPageCount(headers),
          };
        }}
        editable={{
          type: 'multiple',
          onSave: async (key, record, originRow, newLineConfig) => {
            try {
              await updateRole({ data: filterObj(record, originRow) });
            } catch (e) {
              alert(e);
            }
            actionRef.current?.reload();
          },
          onDelete: async (key, record) => {
            if (record.sole === 'admin' || record.sole === 'ordinary') {
              message.warning('此角色为系统内置角色不能删除！');
              actionRef.current?.reload();
              return;
            }
            try {
              await deleteRole({ params: { id: key } });
            } catch (e) {
              alert(e);
            }
            actionRef.current?.reload();
          },
        }}
        tableRender={(props, defaultDom) => {
          props.columns?.map(item => {
            if (item.key === 'option') {
              // @ts-ignore
              item.render = columnsOptions;
            }
            return item;
          });
          return defaultDom;
        }}
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setVisible(true);
              formRef.current?.resetFields();
            }}
            type="primary"
          >
            新建
          </Button>,
        ]}
      />
      <BetaSchemaForm<RoleType>
        formRef={formRef}
        open={visible}
        onOpenChange={setVisible}
        layoutType={theme.formType}
        resize={{
          maxWidth: window.innerWidth * 0.8,
          minWidth: 400,
        }}
        title="新增用户"
        steps={[
          {
            title: 'ProComponent',
          },
        ]}
        rowProps={{
          gutter: [16, 16],
        }}
        colProps={{
          span: 12,
        }}
        grid={theme.formType !== 'LightFilter' && theme.formType !== 'QueryFilter'}
        onFinish={async values => {
          modal.confirm({
            title: '提示',
            content: '是否确认该操作？',
            onOk: async () => {
              const { data } = await createRole({ data: values });
              if (isSuccessCode(data)) {
                setVisible(false);
                actionRef.current?.reload();
              }
            },
          });
        }}
        columns={(theme.formType === 'StepsForm' ? [roleFormItem] : roleFormItem) as any}
      />
    </div>
  );
};

export default Role;
